package com.gitee.magic.core.utils.codec;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
/**
 * @author start
 */
public class Rc4 {

	private static final String RC4 = "RC4";

	/**
	 * RC4从密文解密为明文，输入是经过Base64的
	 */
	public static byte[] decode(String content, String rc4Key) throws UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
		final Cipher c1 = Cipher.getInstance(RC4);
		c1.init(Cipher.DECRYPT_MODE, new SecretKeySpec(rc4Key.getBytes(), RC4));
		return c1.doFinal(Base64.decode(content));
	}

	/**
	 * RC4加密明文（可能包含汉字），输出是经过Base64的
	 */
	public static String encode(byte[] content, String rc4Key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
		Cipher c1 = Cipher.getInstance(RC4);
		c1.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(rc4Key.getBytes(), RC4));
		return Base64.encode(c1.doFinal(content));
	}
	
}
